package com.bookmanger.msg;

/**
 * @author huangfuhao
 * @Date 2024/11/10
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bookmanger.entity.Order;
import com.bookmanger.entity.User;
import com.bookmanger.service.OrderService;
import com.bookmanger.service.UserService;
import com.bookmanger.service.impl.OrderServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 该定时任务用于扫描过期未归还订单并更新其状态，同时将未归还书籍人员状态更新为“禁止借书状态”
 */
@Component
@Slf4j
public class ScheduledTask {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;


    // 每分钟执行一次，Cron表达式：秒 分 时 日 月 星期
    @Scheduled(cron = "* * 0 * * ?")
    public void scanOrders() {
        log.info("定时任务执行");
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //查找超时未归还订单
        LambdaQueryWrapper<Order> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.lt(Order::getEndTime, now);
        orderWrapper.eq(Order::getStatus, 0);
        List<Order> orders = orderService.list(orderWrapper);
        if (!orders.isEmpty()) {
            log.info("{}", orders);
        }

        //将查到的订单借阅状态改为“过期未归还（2）”
        orders.stream().forEach(order -> order.setStatus(2));
        orderService.updateBatchById(orders);
        //同时将过期未归还的学生借阅状态改为“禁止借阅”
        HashMap<Long, User> userMap = new HashMap<>();
        for (Order order : orders) {
            User user = new User();
            user.setId(order.getUserId());
            user.setBanned(1);
            userMap.put(order.getUserId(), user);
        }
        userService.updateBatchById(userMap.values());
    }
}
